import React, { useEffect } from 'react';
import { Dialog, Field, Form, Input, NumberPicker, Radio, Rating } from '@alifd/next';
import { createSellerAccounts } from '../../service';
import { useRequest } from 'ice';

interface Props {
  visible: boolean;
  row: CategoryState.CategoryItem;
  onRefresh: () => void;
  onClose: () => void;
}

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};

const FormItem = Form.Item;

const CreateDialog: React.FC<Props> = (props) => {
  const field = Field.useField([]);
  const { visible, row, onRefresh = () => {}, onClose } = props;

  const { request, loading } = useRequest(createSellerAccounts, {
    manual: true,
    onSuccess: () => {
      onRefresh();
      onClose();
    },
  });

  useEffect(() => {
    if (visible) {
      field.setValues(row);
    } else {
      field.reset();
    }
  }, [visible]);

  const handleOk = () => {
    field.validate((errors, values): void => {
      if (errors) {
        return;
      }
      request({
        ...values,
        nickName: values.nickName.trim(),
        email: values.email?.trim(),
        address: values.address?.trim(),
      });
    });
  };

  return (
    <Dialog
      shouldUpdatePosition
      overflowScroll
      visible={visible}
      onClose={onClose}
      title={`${row.id ? '编辑' : '新增'}卖家`}
      style={{ width: 520 }}
      onOk={handleOk}
      onCancel={onClose}
      okProps={{ loading }}
    >
      <Form fullWidth labelAlign="left" field={field} useLabelForErrorMessage {...formItemLayout}>
        <FormItem label="卖家昵称:" name="nickName" required>
          <Input placeholder="请输入" maxLength={20} />
        </FormItem>
        <FormItem label="联系电话:" format="tel" name="telephone" required>
          <Input placeholder="请输入" />
        </FormItem>
        <FormItem label="邮箱:" format="email" name="email" required>
          <Input placeholder="请输入" />
        </FormItem>
        <FormItem label="联系地址:" name="address" required>
          <Input.TextArea placeholder="请输入" showLimitHint maxLength={100} />
        </FormItem>
        <FormItem name="level" label="卖家星级:" required>
          <Rating allowHalf />
        </FormItem>
        <FormItem label="交易费:" format="number" name="rate" required>
          <NumberPicker placeholder="请输入" min={0} />
          <span style={{ marginLeft: 10 }}>%</span>
        </FormItem>
        <FormItem label="备注:" name="remark">
          <Input.TextArea placeholder="请输入" showLimitHint maxLength={100} />
        </FormItem>
      </Form>
    </Dialog>
  );
};

export default CreateDialog;
